package com.example.aspect;

import com.common.utils.ThreadLocalUtil;
import com.example.annotation.PublicAutoFill;
import com.example.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {
    @Pointcut("execution(* com.example.mapper.*.*(..)) && @annotation(com.example.annotation.PublicAutoFill)")
    public void autoFillPointCut() {}

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws Exception {
        log.info("自动填充");

        //获取操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法的对象
        PublicAutoFill annotation = signature.getMethod().getAnnotation(PublicAutoFill.class);//方法上的注解对象
        OperationType value = annotation.value();

        //获取当前拦截到的方法参数--实体对象
        Object[] args = joinPoint.getArgs();
        if (args.length == 0 || args[0] == null){
            return;
        }
        Object object = args[0];

        //准备赋值的数据
        LocalDateTime now = LocalDateTime.now();
        Long user = ThreadLocalUtil.get();

        //根据当前不同的操作类型，为对应的属性通过反射来赋值
        if (value == OperationType.INSERT){
            Method setUpdateTime = object.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            Method setCreateTime = object.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
            Method setUpdateUser = object.getClass().getDeclaredMethod("setUpdateUser", Long.class);
            Method setCreateUser = object.getClass().getDeclaredMethod("setCreateUser", Long.class);

            setCreateUser.invoke(object,user);
            setUpdateUser.invoke(object,user);
            setCreateTime.invoke(object,now);
            setUpdateTime.invoke(object,now);
        }else if (value == OperationType.UPDATE){
            Method setUpdateTime = object.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            Method setUpdateUser = object.getClass().getDeclaredMethod("setUpdateUser", Long.class);

            setUpdateUser.invoke(object,user);
            setUpdateTime.invoke(object,now);
        }
    }
}
